import {
	createStore
} from 'vuex'

const Store = createStore({

	state() {
		// 上次启动时的用户信息 TODO
		let storageUserInfo = uni.getStorageSync('userInfo') || {
			avatarUrl: 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-dc-site/094a9dc0-50c0-11eb-b680-7980c8a877b8.jpg'
		};
		let storageToken = uni.getStorageSync("token") || ""
		let storageOpenid = uni.getStorageSync("openid") || ""
		return {
			userInfo: storageUserInfo,
			openid: storageOpenid,
			token: storageToken
		}
	},
	// 计算属性
	getters: {
		isLogin(state) {
			return Boolean(state.token.length)
		}
	},
	mutations: {
		login(state, data) {
			console.info("存储登录", data)
			/**
			 * data = {user:user_data,token:token}
			 */
			// 存储用户信息
			let _userInfo = state.userInfo;
			state.userInfo = Object.assign({}, _userInfo, data.user);
			uni.setStorageSync('userInfo', state.userInfo);
			// 存储 token
			state.token = data.token
			uni.setStorageSync('token', state.token)
			// 存储 openid
			state.openid = data.openid
			uni.setStorageSync('openid', state.openid)
		},
		logout(state) {
			/**
			 * 清空存储的登录数据
			 */
			state.userInfo = {};
			state.openid = "";
			state.token = "";
			uni.removeStorageSync('token');
			uni.removeStorageSync('openid');
		},
	}
})

export default Store;
